package com.revzone.demo001.LogModule.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.revzone.demo001.LogModule.mapper.AccessLogsMapper;
import com.revzone.demo001.entity.LogEntity.AccessLogs;
import com.revzone.demo001.entity.LogEntity.AccessLogsDTO;
import com.revzone.demo001.entity.OtherEntity.BaseEntity;
import com.revzone.demo001.entity.OtherEntity.PageResult;
import com.revzone.demo001.entity.OtherEntity.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("logs")
@Api(tags = "log日志管理", description = "用于log日志管理的相关API")
public class accessLogsController {
    @Autowired
    AccessLogsMapper accessLogsMapper;
    @ApiOperation(value = "用于log日志的查询接口")
    @PostMapping(value="/getLogsPage", produces = "application/json;charset=UTF-8")
    @RequiresRoles(logical = Logical.OR, value = {"root","user", "admin"})
    public R getLogsPage(@RequestBody(required = false) AccessLogsDTO accessLogsDTO) {
        HashMap<String, Object> map = new HashMap<>();
        AccessLogs accessLogs = new AccessLogs();

        Page<AccessLogs> accessLogsPage;
        try {
            if(accessLogsDTO == null)accessLogsDTO = new AccessLogsDTO(); // 如果accessLogsDTO为null，则新建一个对象
            Page<AccessLogs> page = new Page<>(accessLogsDTO.getCurrentPage(),accessLogsDTO.getPageSize());
            BeanUtils.copyProperties(accessLogsDTO,accessLogs);
            QueryWrapper<AccessLogs> wrapper = BaseEntity.getQueryWrapper(accessLogs);
            accessLogsPage = accessLogsMapper.selectPage(page, wrapper);
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }

        // 将查询结果封装到 PageResult 类型的对象中
        PageResult<AccessLogs> result = new PageResult<AccessLogs>(accessLogsPage);
        map.put("data",result);
        return R.ok(map);
    }

}
